package com.ph.elec.page;

import java.text.DateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.ph.elec.gwt.post.server.FrontNewsEntity;
import com.ph.elec.template.BasePage;

import dan.util.dstore.PersistenceUtils;

public class IndexPage extends BasePage {
	
	public List<FrontNewsEntity> news = null;

	public IndexPage() {
		// Set Page Properties
		title = "Welcome";
		keywords = "";
		description = "";
	}
	
	@Override
	public void onInit() {
		super.onInit();
		news = getNewsItems();
	}

	@SuppressWarnings("unchecked")
	private List<FrontNewsEntity> getNewsItems() {
		// Load all news items from Data Store
		PersistenceManager db = PersistenceUtils.mgr();
		List<FrontNewsEntity> news =  (List<FrontNewsEntity>) 
				db.newQuery("SELECT FROM com.ph.elec.gwt.post.server.FrontNewsEntity ").execute();
		Collections.sort(news, new NewsOrder());
		for (FrontNewsEntity item : news) {
			item.setTimePost(DateFormat.getDateInstance(DateFormat.MEDIUM).
					format(new Date(Long.valueOf(item.getTimePost().substring(1)))));
		}
		return news;
	}
	
	private class NewsOrder implements Comparator<FrontNewsEntity> {

		public int compare(FrontNewsEntity o1, FrontNewsEntity o2) {
			return (int) (Long.valueOf(o2.getTimePost().substring(1)) -
					Long.valueOf(o1.getTimePost().substring(1)));
		}
		
	}

}
